<?php
require_once('pworks/db/DsConfig.class.php');
require_once('pworks/db/DaoConfig.class.php');
require_once('pworks/db/DsConfig.class.php');
require_once('pworks/db/DaoConfig.class.php');
/**
 * This class is used to get dao config elements from a xml file:
 * <li>DS configurations</li>
 * <li>DAO configurations</li>
 * XML format looks like:
 * <dao-config>
 *     <datasources>
 *         <ds id="local.mysql" 
 *            type="mysql"
 *            driver="mysqli"
 *            host="local" 
 *            user="root" 
 *            password="123" 
 *            db="mysql"
 *            charset="utf8"/>
 *    </datasources>
 *    <daos>
 *        <dao name="db"
 *            ds="local.mysql"
 *            class="Mysqli_DbDao"
 *            src="mysql/dao/Mysqli_DbDao.class.php"/>
 *    </daos>
 * </dao-config>
 */
class XMLConfigLoader {

	private $_configFilePath;
	private $_dom;

	private $_dsConfigs;
	private $_daoConfigs;
	
	public function getDsConfigs() {
		return $this->_dsConfigs;
	}
	
	public function getDaoConfigs() {
		return $this->_daoConfigs;
	}
	
	/**
	 * load the XMLConfig file and parse.
	 *
	 * @param string $configFile : XMLFilePath muss be fullPath.
	 */
	public function load($configFile)
	{
		$this->_configFilePath = $configFile;
		$this->_dom = new DOMDocument();
		$this->_dom->load($configFile);
		$this->_init();
	}

	/**
	 * parse XMLFilePath set DataSources and DAOs.
	 *
	 */
	private function _init()
	{
		$xpath = new DOMXPath($this->_dom);
		//set DataSources
		$this->getAllDsConfig($xpath->query('//dao-config/datasources/ds'));

		//set DAOs
		$this->getAllDaoConfig($xpath->query('//dao-config/daos/dao'));
	}
	
	private function getAllDsConfig(DOMNodeList $dsnNodes)
	{
		$this->_dsConfigs = array();
		foreach ($dsnNodes as $dsnNode)
		{
			$ds = new DsConfig();
			$ds->id = $dsnNode->getAttribute('id');
			$ds->type = $dsnNode->getAttribute('type');
			$ds->driver = $dsnNode->getAttribute('driver');
			
			$ds->host = $dsnNode->getAttribute('host');
			$ds->user = $dsnNode->getAttribute('user');
			$ds->password = $dsnNode->getAttribute('password');
			$ds->db = $dsnNode->getAttribute('db');
			
			$ds->charset = $dsnNode->getAttribute('charset');
			
			$this->_dsConfigs[$ds->id] = $ds;
		}
	}

	private function getAllDaoConfig(DOMNodeList $daoConfigNodes)
	{
		foreach ($daoConfigNodes as $daoConfigNode)
		{
			$daoConfig = new DaoConfig();
			
			$daoConfig->name = $daoConfigNode->getAttribute('name');
			$daoConfig->ds =  $daoConfigNode->getAttribute('ds');
			
			$daoConfig->clzName = $daoConfigNode->getAttribute('class');
			$daoConfig->src = $daoConfigNode->getAttribute('src');
			$this->_daoConfigs[$daoConfig->name] = $daoConfig;
		}
	}
}
?>
